package com.example.demo.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Locale;

/**
 * @author Liunh
 */
@Slf4j
public class EnvUtil {

    public static String getOsType() {
        String osType = null;
        String os = System.getProperty("os.name");
        if (os != null && os.toLowerCase().startsWith("win")) {
            //Windows操作系统
            osType = "Windows";
        } else if (os != null && os.toLowerCase().startsWith("linux")) {
            //Linux操作系统
            osType = "Linux";
        } else {
            //其它操作系统
            osType = "Linux";
        }
        return osType;
    }

    public static String getOsName() {
        String osName = System.getProperties().getProperty("os.name").toLowerCase(Locale.ROOT);
        if (osName.contains("linux")) {
            log.info(">>>>>> os name is linux");
        } else if (osName.contains("win")) {
            log.info(">>>>>> os name is Windows");
        } else {
            log.info(">>>>>> os name is :{}", osName);
        }
        return osName;
    }

    public static boolean isLinux() {
        if (getOsName().contains("linux")) {
            return true;
        }
        return false;
    }

    public static boolean isWindows() {
        if (getOsName().startsWith("win") || getOsName().contains("win")) {
            return true;
        }
        return false;
    }

    public static boolean exeShellFile(String scriptPath) {
        try {
            if (StringUtils.isNotBlank(scriptPath) && isLinux()) {
                if (scriptPath.startsWith("/")) {
                    scriptPath = scriptPath.substring(1, scriptPath.length());
                }
                scriptPath = "sh ./" + scriptPath;
                Process ps = Runtime.getRuntime().exec(scriptPath);
                ps.waitFor();
            }
            return true;
        } catch (Exception e) {
            log.error(">>>>>> execute script error !", e);
        }
        return false;
    }

    public static boolean exeShellCommand(String scriptPath) {
        try {
            if (StringUtils.isNotBlank(scriptPath) && isLinux()) {
                Process ps = Runtime.getRuntime().exec(scriptPath);
                ps.waitFor();
            }
            return true;
        } catch (Exception e) {
            log.error(">>>>>> execute script error !", e);
        }
        return false;
    }


}
